package com.myway.components.weather.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import javax.ws.rs.core.HttpHeaders;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.myway.dto.weather.DTOResults;
import com.myway.dto.weather.DTOTelephone;
import com.myway.dto.weather.DTOTelephoneResult;
import com.myway.dto.weather.DTOWeather;
import com.myway.utils.GsonUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

public class weatherUtil  {
	private static Log log = LogFactory.getLog( weatherUtil.class );
	public static final String url = "http://api.map.baidu.com/telematics/v3/weather";
	public static final String ak = "OohuPfRQLxGVyPsu0mQvrFsUtiMA9QVu";
	
	public static final String telephoneApk = "880b0754945c94ad71172a2e68d03949";
	
	private static final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
	
	public static final String phoneUrl = "http://apis.baidu.com/apistore/mobilephoneservice/mobilephone";
	/**
	 * 天气查询 - 2.查询天气信息
	 * @return
	 */
	public static List<DTOResults> queryWeather(String city){
		String requesturl = url+"?location="+city+"&output=json&ak="+ak;
		String result = sendPost(requesturl, null);
		DTOWeather dtoWeather = gson.fromJson(result, DTOWeather.class);
//		解析并判断
		int error = dtoWeather.getError();
		String status = dtoWeather.getStatus();
		//error=0且status=success时为成功
		if(error == 0 && status.equals("success")){
			return dtoWeather.getResults();
		}else{
			return null;
		}
	}
	
	public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
            // 设置通用的请求属性
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            //设置http请求的数据7类型
            conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, "text/html");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            // 获取URLConnection对象对应的输出流
            if(null != param && !"".equals(param)){
            	 out = new PrintWriter(conn.getOutputStream());
                 // 发送请求参数
                 out.print(param);
                 // flush输出流的缓冲
                 out.flush();
            }
            // 定义BufferedReader输入流来读取URL的响应,"UTF-8"
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null ) {
                result += new String(line.getBytes());
            }
        } catch (Exception e) {
            log.info("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }   
	
	
	/**
	 * 天气查询 - 2.查询天气信息
	 * @return
	 */
	public static DTOTelephone queryTelephone(DTOTelephoneResult phoneParam){
		StringBuffer httpArg = new StringBuffer("tel=");
		try {
			if(null!=phoneParam&&!"".equals(phoneParam.getTelString())){
				String  phone  = httpArg.append(phoneParam.getTelString()).toString();
				log.info("查询号码归属地phone"+phone);
				DTOTelephone dTOTelephone = new DTOTelephone();
				//百度方法查询(收费，已关闭)
//				String jsonResult = requestTelephone(phoneUrl, phone);
//				dTOTelephone=gson.fromJson(jsonResult, DTOTelephone.class);
				//淘宝方法查询
				String jsonResult=requestTaobaoTelephone(phone);
				DTOTelephoneResult dTOTelephoneResult = GsonUtil.fromJson(jsonResult, DTOTelephoneResult.class);
				dTOTelephone.setRetData(dTOTelephoneResult);
				return dTOTelephone;
			}
			return null;
		} catch (JsonSyntaxException e) {
			log.info("json转化异常");
			return null;
		}
	}
	/**
	 * @param urlAll
	 *            :请求接口
	 * @param httpArg
	 *            :参数
	 * @return 返回结果
	 */
	public static String requestTelephone(String httpUrl, String httpArg) {
		BufferedReader reader = null;
		String result = null;
		StringBuffer sbf = new StringBuffer();
		httpUrl = httpUrl + "?" + httpArg;
		
		try {
			URL url = new URL(httpUrl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, "text/html");
			connection.setRequestProperty("Accept-Charset", "UTF-8");
			// 填入apikey到HTTP header
			connection.setRequestProperty("apikey",  telephoneApk);
			connection.connect();
			InputStream is = connection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String strRead = null;
			while ((strRead = reader.readLine()) != null) {
				sbf.append(strRead);
				sbf.append("\r\n");
			}
			reader.close();
			result = sbf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * @名称：requestTaobaoTelephone 
	 * @描述：淘宝号码归属地查询(免费)
	 * @param httpArg
	 * @return
	*/
	public static String requestTaobaoTelephone(String httpArg) {
		BufferedReader reader = null;
		String result = null;
		StringBuffer sbf = new StringBuffer();
		String httpUrl = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?" + httpArg;
		
		try {
			URL url = new URL(httpUrl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, "text/html");
			connection.setRequestProperty("Accept-Charset", "GBK");
			// 填入apikey到HTTP header
			connection.setRequestProperty("apikey",  telephoneApk);
			connection.connect();
			InputStream is = connection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, "GBK"));
			String strRead = null;
			while ((strRead = reader.readLine()) != null) {
				sbf.append(strRead);
				sbf.append("\r\n");
			}
			reader.close();
			result = sbf.toString();
			result=result.replaceAll("__GetZoneResult_ =", "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
